package com.pagoda.nerp.trade.app.quality.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pagoda.nerp.trade.app.quality.utils.InvokeQualityPartUtils;
import com.pagoda.nerp.trade.common.ConstantDefine;
import com.pagoda.nerp.trade.common.exception.BaseException;
import com.pagoda.nerp.trade.common.objectutil.PropertyConfigurer;
import com.pagoda.nerp.trade.common.wx.handler.WxMessageHandler;
import com.pagoda.nerp.trade.dao.MdAccountDao;
import com.pagoda.nerp.trade.dao.MdFeedbackDao;
import com.pagoda.nerp.trade.dao.MdQualityRecordDao;
import com.pagoda.nerp.trade.entity.MdQualityRecord;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ww on 2016/12/27.
 */
@Component
public class QueryQualityReport extends QuartzJobBean {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MdQualityRecordDao qualityRecordDao;
    @Autowired
    private MdFeedbackDao feedbackDao;
    @Autowired
    private MdAccountDao accountDao;


    /**
     * 功能：每十分钟调用质检平台接口查询质检状态为D(等待质检)的记录的最新状态
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        List<MdQualityRecord> qualityRecordList = qualityRecordDao.queryQualityRecordListByStatus(ConstantDefine.QUALITY_STATUS_WAIT_TEST);
        if (qualityRecordList == null) {
            return;
        }

        //拼接resp
        StringBuilder codeString = new StringBuilder();
        for (MdQualityRecord temp : qualityRecordList) {
            codeString.append(temp.getQualityPlatId()).append(",");
        }

        Map<String,String> paraMap = new HashMap<String,String>();
        paraMap.put("codes", codeString.substring(0, codeString.length() - 1));

        //调用质检平台接口： 批量查询质检结果
        JSONObject jsonObject = InvokeQualityPartUtils.invokeQualityPart(paraMap, PropertyConfigurer.parseStr("quality.report.result.url"));
        if (jsonObject.getIntValue("code") != 0) {
            logger.error("QueryQualityReport --> executeInternal:Invoke quality part failed!code=" + jsonObject.get("code"));
            throw new BaseException(jsonObject.getString("message"));
        }
        JSONArray jsonArray = jsonObject.getJSONArray("data");

        MdQualityRecord qualityRecord = new MdQualityRecord();

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject map = jsonArray.getJSONObject(i);
            if (map.getIntValue("status") == 1) {
                //通过
                qualityRecord.setStatus(ConstantDefine.QUALITY_STATUS_PASS);
            } else if (map.getInteger("status") == 2) {
                //失败
                qualityRecord.setStatus(ConstantDefine.QUALITY_STATUS_FAILED);
            } else {
                continue;
            }

            //修改状态
            qualityRecord.setQualityRecordNo(map.getString("code"));
            int result = qualityRecordDao.updateStatusByCode(qualityRecord);
            if (result < 0) {
                logger.error("QueryQualityReport --> executeInternal: failed to update quality record status !");
                continue;
            }

            MdQualityRecord mdqualityRecord = qualityRecordDao.queryQualityRecordAndGoodsNameByCode(map.getString("code"));
            if (mdqualityRecord == null) {
                logger.error("QueryQualityReport --> executeInternal: failed to query quality record by code !code={}", map.getString("code"));
                continue;
            }

            //查询供应商对应的有openid的子账户
            List<String> openIdList = accountDao.selectOpenIdByVendorId(mdqualityRecord.getVendorId());
            if (openIdList == null || openIdList.size() == 0) {
                continue;
            }

            //组装模板信息
            String first = "您的质检报告{{" + map.getString("code") + "}}已经提交，请登录百果园交易平台查看详情。";
            String testItem = mdqualityRecord.getGoodsName();
            String reportCode = map.getString("code");
            String datetime = new SimpleDateFormat("yyyy-MM-dd").format(new Timestamp(System.currentTimeMillis()));
            for (String tempOpenId : openIdList) {
                WxMessageHandler.sendQualityPublishNotifyMsg(first, testItem, reportCode, datetime, null, tempOpenId);
            }
        }
    }

}
